﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils.Text.Internal;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using NjaNjam.MongoRepository;
using NjamNjam.Model.Entities;
using NjamNjamAdminApp.ImageService;
using NjamNjamAdminApp.Interfaces;
using System.Linq;
using NjamNjamAdminApp.Properties;

namespace NjamNjamAdminApp.Views
{
    public partial class RestoraniView : DevExpress.XtraEditors.XtraForm, IView
    {
        private readonly BindingList<VrstaRestorana> m_VrsteRestorana = new BindingList<VrstaRestorana>();

        private readonly  BindingList<Restoran> m_Restorani = new BindingList<Restoran>();

        private List<Ponuda> m_Ponuda; 

        private readonly MongoRepository m_MongoRepository = new MongoRepository();
 
        public RestoraniView()
        {
            InitializeComponent();
            vrstaRestoranaBindingSource.DataSource = m_VrsteRestorana;
            restoranBindingSource.DataSource = m_Restorani;
            restoranBindingSource.CurrentChanged += (s, e) => ShowOnMap();
            m_Restorani.AddingNew += (s, e) =>
                                     {
                                         var restoran = new Restoran();
                                         if (m_Restorani.Count == 0)
                                         {
                                             restoran.Id = 1;
                                         }
                                         else
                                         {
                                             restoran.Id = m_Restorani.Max(x => x.Id) + 1;

                                         }
                                         e.NewObject = restoran;
                                     };
            string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
            string filePath = Path.Combine(appPath, "Web/Map.htm");
            webBrowser1.Url = new Uri(filePath);
            btnMap.Click += (s, e) => ShowOnMap();
            btnSearch.Click += (s, e) => OnAddressSearch();
            gridView2.KeyDown += (s, e) =>
                                 {
                                     if (e.KeyCode == Keys.Delete && gridView2.FocusedColumn == gridView2.Columns[0])
                                     {
                                         var ponudaRestorana = gridView2.GetFocusedRow() as PonudaRestorana;
                                         if (ponudaRestorana != null)
                                         {
                                             IzabraniRestoran.Ponuda.Remove(ponudaRestorana);
                                             ponudaBindingSource.ResetBindings(true);
                                         }
                                     }
                                 };
            ponudaBindingSource.AddingNew += (s, e) =>
                                             {
                                                 long id = 1;
                                                 if (IzabraniRestoran.Ponuda.Count > 0)
                                                 {
                                                     id = IzabraniRestoran.Ponuda.Max(x => x.Id) + 1;
                                                 }
                                                 e.NewObject = new PonudaRestorana {Id = id};
                                             };
            repositoryItemImageComboBox1.SelectedValueChanged += (s, e) =>
                                                                 {
                                                                     var editor = (ImageComboBoxEdit) s;
                                                                     if (IzabraniRestoran.Ponuda.Any(x => x.Ponuda == (editor.EditValue)))
                                                                     {
                                                                         ((IShell)MdiParent).ShowWarning("Izabrana ponuda je već uneta");
                                                                     }
                                                                 };

        }

        private void OnAddressSearch()
        {
            var restoran = IzabraniRestoran;
            if (restoran != null)
            {
                var searchTerm = new StringBuilder();
                if (!String.IsNullOrEmpty(restoran.Adresa))
                {
                    searchTerm.Append(restoran.Adresa.Trim());
                }
                if (searchTerm.Length > 0)
                {
                    searchTerm.Append(",");
                }
                if (!String.IsNullOrEmpty(restoran.Mesto))
                {
                    searchTerm.Append(restoran.Mesto.Trim());
                }
                if (searchTerm.Length == 0) return;
                using(var dlg = new AddressSearchView(searchTerm.ToString()))
                {
                    dlg.ShowDialog(this);
                    if (dlg.SearchResult != null)
                    {
                        restoran.Latituda = dlg.SearchResult.Latitude;
                        restoran.Longituda = dlg.SearchResult.Longitude;
                    }
                }
            }
        }

        private void ShowOnMap()
        {
            var restoran = IzabraniRestoran;
            if (restoran != null)
            {
                webBrowser1.Document.InvokeScript("pozicioniraj", new object[] {restoran.Latituda, restoran.Longituda, true});
            }
            
        }

        private Restoran IzabraniRestoran
        {
            get { return restoranBindingSource.Current as Restoran; }
        }

        public void NoviUnos()
        {
            m_Restorani.AddNew();
            restoranBindingSource.MoveLast();
        }

        public void Sacuvaj()
        {
            var restoran = IzabraniRestoran;
            if (restoran != null)
            {
                m_MongoRepository.Sacuvaj(restoran);
            }
        }

        public void Obrisi()
        {
            var restoran = restoranBindingSource.Current as Restoran;
            if (restoran != null)
            {
                m_MongoRepository.Obrisi(restoran);
                m_Restorani.Remove(restoran);
            }
        }

        public void Osvezi()
        {
            UcitajVrsteRestorana();
            UcitajRestorane();
            UcitajPonudu();
        }

        public void Izvezi()
        {
            using(var svc = new ImageServiceClient("Http"))
            {
                try
                {
                    foreach (var restoran in m_Restorani)
                    {
                        var response = svc.SacuvajSlikuRestorana(new SaveImageRequest { Id = restoran.Id, Image = restoran.Slika });
                        if (response.ErrorMessage != null)
                        {
                            ((IShell)MdiParent).ShowWarning("Nesupešan izvoz slike " + restoran.Naziv + ": " + response.ErrorMessage);
                            break;
                        }
                    }
                }
                catch (Exception exc)
                {
                    ((IShell)MdiParent).ShowWarning("Nesupešan izvoz slike: " + exc.Message);
                }
            }
        }

        private void UcitajPonudu()
        {
            m_Ponuda = m_MongoRepository.Ponuda().ToList();
            repositoryItemImageComboBox1.Items.Clear();
            imageList1.Images.Clear();
            for (int index = 0; index < m_Ponuda.Count; index++)
            {
                var ponuda = m_Ponuda[index];
                if (ponuda.Slika != null)
                {
                    imageList1.Images.Add(Image.FromStream(new MemoryStream(ponuda.Slika)));
                } else
                {
                    imageList1.Images.Add(Resources.camera_photo);
                }
                repositoryItemImageComboBox1.Items.Add(new ImageComboBoxItem(ponuda.Naziv, index){Value = ponuda});
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            Osvezi();
        }

        private void UcitajRestorane()
        {
            var restorani = m_MongoRepository.Restorani();
            m_Restorani.Clear();
            foreach (var restoran in restorani)
            {
                m_Restorani.Add(restoran);
            }
        }

        private void UcitajVrsteRestorana()
        {
            var vrsteRestorana = m_MongoRepository.VrsteRestorana();
            m_VrsteRestorana.Clear();
            foreach (var vrstaRestorana in vrsteRestorana)
            {
                m_VrsteRestorana.Add(vrstaRestorana);
            }
        }
    }
}